package com.example.wiki.auth.service;

import com.example.wiki.auth.controller.UserController;
import com.example.wiki.auth.entity.TokenBean;
import com.example.wiki.resp.CommonResp;
import com.example.wiki.resp.GiteeUserTokenResp;


import com.google.common.base.Utf8;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.http.*;
import org.springframework.stereotype.Service;


import org.springframework.web.client.RestTemplate;

import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Service
public class GiteeOAuthService {


    @Value("${gitee.client-id}")
    private String clientId;

    @Value("${gitee.client-secret}")
    private String clientSecret;

    @Value("${gitee.redirect-uri}")
    private String redirectUri;

    @Value("${gitee.token-url}")
    private String tokenUrl;
    private static final Logger Log = LoggerFactory.getLogger(UserController.class);




    /**
     * 使用授权码从Gitee服务器交换Access Token。generalResponse.setData
     *
     * @param code 授权码
     * @return Access Token相关信息，具体结构取决于Gitee的响应
     */
    public TokenBean exchangeCodeForAccessToken(String code) {
        System.out.println("code:" + code);
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> requestBody =new HashMap<>();
        requestBody.put("code", code);
        requestBody.put("client_id", clientId);
        requestBody.put("redirect_uri",redirectUri);
        requestBody.put("client_secret", clientSecret);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String,String>>  httpEntity = new HttpEntity<Map<String, String>>(requestBody, headers);

        String url ="https://gitee.com/oauth/token?grant_type=authorization_code";

        return restTemplate.postForObject(url, httpEntity, TokenBean.class);
    }

    public GiteeUserTokenResp tokenToUserInfo(TokenBean tokenBean){
        String accessToken =  tokenBean.getAccess_token();
        Log.info("ss",accessToken);
        String url ="https://gitee.com/api/v5/user?access_token={token}";
        RestTemplate restTemplate = new RestTemplate();


        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity request = new HttpEntity(headers);

        ResponseEntity<GiteeUserTokenResp> response =restTemplate.exchange(url,HttpMethod.GET,request, GiteeUserTokenResp.class,accessToken);


        return response.getBody();


    }


//    /**
//     * 使用授权码从Gitee服务器交换Access Token。generalResponse.setData
//     *
//     * @param code 授权码
//     * @return Access Token相关信息，具体结构取决于Gitee的响应
//     */
//    public Mono<CommonResp<String>> exchangeCodeForAccessToken(String code) {
//
//        System.out.println("code:" + code);
//        Mono<ResponseEntity<String>> monoResponseEntity = webClientBuilder.build()
//                .post()
//                .uri(tokenUrl)
//                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
//                .body(BodyInserters.fromFormData("grant_type", "authorization_code")
//                        .with("code", code)
//                        .with("client_id", clientId)
//                        .with("client_secret", clientSecret)
//                        .with("redirect_uri", redirectUri))
//                .retrieve()
//                .toEntity(String.class)
//                .onErrorResume(e -> Mono.error(new RuntimeException("Failed to exchange code for access token", e)));
//
//        return monoResponseEntity.map(responseEntity -> {
//            System.out.println("responseEntity:" + responseEntity.getBody());
//            HttpStatus status = responseEntity.getStatusCode();
//            String responseBody = responseEntity.getBody();
//            // 根据HTTP状态码设定code和message
//
//            String message = status.is2xxSuccessful() ? "Success" : "Error occurred";
//
//            CommonResp<String> commonResp = new CommonResp<>();
//            commonResp.setMessage(message);
//            commonResp.setStatus(status.value());
//            commonResp.setContent(responseBody);
//
//            return commonResp;
//        }).onErrorResume(e -> Mono.just(
//                new CommonResp<>()
//                        .setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value())
//                        .setMessage("An error occurred while processing the request.")
//                        .setContent(null)
//        ));;
//
//
//    }
}